package com.wms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wms.bean.PageBean;
import com.wms.dto.OutZhiJieDTO;
import com.wms.entity.*;
import com.wms.mapper.WaxMaterialMapper;
import com.wms.mapper.OutMapper;
import com.wms.service.OutService;
import com.wms.utils.Create;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class OutServiceImpl implements OutService {
    @Autowired
    OutMapper outMapper;
    @Autowired
    Create create;
    @Autowired
    WaxMaterialMapper waxMaterialMapper;


    // 分页+条件查询
    @Override
    public PageBean<List<Map<String, Object>>> chaTuiHuo(Integer id, Integer status, String startTime,
                                                         String endTime,Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);
        List<Map<String,Object>> list=outMapper.chaTuiHuo(id,status,startTime,endTime,pageNum,pageSize);
        PageInfo info=new PageInfo(list);
        return new PageBean(pageNum,pageSize,info.getTotal(),list);
    }

//    @Override
//    public PageBean ChanShangZhi(String startTime, String endTime, int type, Integer id, Integer status, Integer chukuType, Integer category, String warmarea, String tiem, String reason, Integer page, Integer pageSize) {
//        PageHelper.startPage(page,pageSize);
//        List list=outMapper.ChanShangZhi(startTime,endTime,type,id,status,chukuType,category,warmarea,tiem,reason,page,pageSize);
//        PageInfo info=new PageInfo<>(list);
//        return new PageBean(page,pageSize,info.getTotal(),list);
//    }


    @Override
    public PageBean ChanShangZhi(OutZhiJieDTO outZhiJieDTO) {
        PageHelper.startPage(outZhiJieDTO.getPage(),outZhiJieDTO.getPageSize());
        List list=outMapper.ChanShangZhi(outZhiJieDTO);
        PageInfo info=new PageInfo<>(list);

        return new PageBean(outZhiJieDTO.getPage(),outZhiJieDTO.getPageSize(),info.getTotal(),list);
    }

    /**
     * 实现直接出库 新增任务功能
     * @param task 出库任务
     * @param direct 直接出库记录
     * @param details 出库明细列表
     * @return
     */
    @Transactional
    @Override
    public Integer createStockOut(DStockOutTask task, BStockOutDirect direct, List<BStockOutTaskDetail> details) {
        // 校验明细列表
        if (details == null || details.isEmpty()) {
            throw new IllegalArgumentException("出库明细不能为空");
        }

        // 计算所有明细数量的总和      赋值给总明细
        int totalNumber = 0;
        for (BStockOutTaskDetail detail : details) {
            if (detail.getNumber() == null || detail.getNumber() <= 0) {
                throw new IllegalArgumentException("明细数量必须为正数");
            }
            totalNumber += detail.getNumber();
        }

        //生成有规则的任务id
        String newid=create.IDcreate("ZJ");
        //直接出库
        BStockOutDirect BOD=new BStockOutDirect();
        BOD.setId(newid);
        BOD.setWarmarea(direct.getWarmarea());
        BOD.setTaskNum(totalNumber);
        BOD.setReason(direct.getReason());
        BOD.setCategory(direct.getCategory());
        outMapper.insertStockOutDirect(BOD);
        //出库任务
        DStockOutTask DSOT=new DStockOutTask();
        DSOT.setCreateBy(task.getCreateBy());
        DSOT.setTaskCode(newid);
        DSOT.setStatus(task.getStatus());
        DSOT.setTiem(task.getTiem());
        DSOT.setIsdel(task.getIsdel());
        outMapper.insertStockOutTask(DSOT);
        //出库明细
        List<BStockOutTaskDetail> taskDetails = new ArrayList<>();
        for (BStockOutTaskDetail detail : details) {
            BStockOutTaskDetail taskDetail = new BStockOutTaskDetail();
            taskDetail.setTaskid(newid); // 关联任务ID
            taskDetail.setCategory(detail.getCategory());
            taskDetail.setProductcode(detail.getProductcode());
            taskDetail.setProductname(detail.getProductname());
            taskDetail.setCkName(detail.getCkName());
            taskDetail.setLocationName(detail.getLocationName());
            taskDetail.setSpec(detail.getSpec());
            taskDetail.setNumber(detail.getNumber());
            taskDetail.setUnit(detail.getUnit());
            taskDetail.setBatch(detail.getBatch());
            taskDetail.setOutTime(detail.getOutTime() != null ? detail.getOutTime() : new Date());
            taskDetail.setExtInfo(detail.getExtInfo());
            taskDetail.setWuliaoId(detail.getWuliaoId());
            taskDetails.add(taskDetail);
        }
        outMapper.batchInsertTaskDetails(taskDetails);


        return 1;
    }

    //所有出库明细
    @Override
    public PageBean Allmingxi(int page, int pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Map<String,Object>> list=outMapper.Allmingxi();
        PageInfo info=new PageInfo<>(list);
        return new PageBean(page,pageSize,info.getTotal(),list);
    }


    //退货任务添加
    @Override
    public void save(OutStorePurchase outStorePurchase) {
        //任务编号
        String taskCode=create.IDcreate("TH");
        outStorePurchase.setTaskCode(taskCode);

        //保存主表 返回任务id
        StringBuilder sb=new StringBuilder("");
        outStorePurchase.getOutStoreTaskDetails().forEach(el->{
            sb.append(el.getProductname());
            sb.append("(");
            sb.append(el.getSpec());
            sb.append(")");
            sb.append(el.getNumber());
            sb.append(el.getUnit());
            sb.append(";");
        });
        outStorePurchase.setTiem(sb.toString());
        int n=outMapper.save(outStorePurchase);
        if (n == 0) {
            throw new IllegalArgumentException("退货父表保存失败"); // 可替换为自定义异常
        }

        //保存副标
        String newid= taskCode;
        outStorePurchase.setId(newid);
        int m=outMapper.saveZi(outStorePurchase);
        if (m == 0) {
            throw new IllegalArgumentException("退货子表保存失败"); // 可替换为自定义异常
        }

        //保存出库明细
        int p=outMapper.THall(taskCode,outStorePurchase.getOutStoreTaskDetails());
        if (p == 0) {
            throw new IllegalArgumentException("退货明细保存失败"); // 可替换为自定义异常
        }

        //锁定库存 遍历明细 生成出库记录  锁定库存
        outStorePurchase.getOutStoreTaskDetails().forEach(el->{
            //根据物料编码 入库时间升序
            List<BatchStore> list=outMapper.queryBatchNum(el.getProductcode());

            if (list.isEmpty()){
                throw new IllegalArgumentException(el.getProductcode()+"库存不足"); // 可替换为自定义异常
            }

            //要出库的数量
            int num=el.getNumber();
            int rs;
            for (int i=0,len=list.size();i<len;i++){
                //获取当前批次
                BatchStore batchStore=list.get(i);
                if (num<batchStore.getAvailablenum()){
                    //满足提交需求
                    //该批次库存冻结num个商品    可用-num 冻结+num
                    rs=outMapper.lockStore(batchStore.getId(),num);
                    if (rs==0){throw new IllegalArgumentException("冻结失败");}
                    //总库存更新 可用-num 冻结+num

                    //生成出库记录

                }else {
                    //不满足
                    // 该批次冻结num个  可用数量=0 冻结+（可用量）

                    //剩余要出库量  num=num-当前批次可用量

                    //总库存 可用量-当前批次可用量  冻结数+当前批次可用量  根据物料id

                    //出库记录

                    //进入下个循环
                }
            }

        });
    }





    //增加出库任务 选货品
    @Override
    public PageBean outMaterial(int page,int pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Map<String,Object>> list= waxMaterialMapper.outMaterial();
        PageInfo info=new PageInfo<>(list);
        return new PageBean<>(page,pageSize,info.getTotal(),list);
    }


    //根据id查找直接出库任务明细
    @Override
    public PageBean outZJdeatil(String id,int page,int pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Map> list=outMapper.outZJdeatil(id);
        PageInfo info=new PageInfo<>(list);
        return new PageBean<>(page,pageSize,info.getTotal(),list);
    }

    //出库记录
    @Override
    public List<Map> outjilu(Integer productId) {
        List<Map> list=outMapper.outjilu(productId);
        return list;
    }
}
